/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.address;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

import com.jnetx.javax.sip.util.ByteArrayUtil;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
class HttpURIParser extends URIParserBase<HttpURIImpl> {
    private static final Log logger = LogFactory.getLog(HttpURIParser.class);
    private final static byte[] two_slashes = "//".getBytes();

    protected Log getLogger() {
        return logger;
    }

    HttpURIParser() {
    }

    // http://www.jnetx.ru:8080/docs/ss.doc
    public HttpURIImpl parse(byte[] data, int start, int end, HttpURIImpl uriObject) throws ParseException {
        if (uriObject == null) uriObject = new HttpURIImpl();
        final int index1 = ByteArrayUtil.firstOccurence(data, ':', start, end);
        if (index1 == -1)
            fail("The URI scheme cannot be recognized!", start);
        final String scheme = new String(data, start, index1 - start);
        if (scheme.equals(""))
            fail("Malformed URI!", start);
        if (scheme.equals("http"))
            uriObject.setSecure(false);
        else if (scheme.equals("https"))
            uriObject.setSecure(true);
        else
            fail("Unknown URI scheme: " + scheme, start);
        if (!ByteArrayUtil.startsWith(data, index1+1, end, two_slashes, 0, 2))
            fail("The URI is malformed!", index1+1);
        final int hostStart = index1+3; //where host info starts
        int hostEnd = ByteArrayUtil.firstOccurence(data, '/', hostStart, end);
        if (hostEnd==-1)
            hostEnd=end;
        else
            uriObject.setPath(new String(data, hostEnd, end-hostEnd));
        parseHostInfo(data, hostStart, hostEnd, uriObject);
        return uriObject;
    }

    private void parseHostInfo(byte[] data, int start, int end, HttpURIImpl uriObject) throws ParseException {
        final int index = ByteArrayUtil.firstOccurence(data, ':', start, end);
        if (index != -1) {
            //port is present
            uriObject.setHost(new String(data, start, index - start));
            try {
                uriObject.setPort((int)ByteArrayUtil.parseInteger(data, index + 1, end));
            } catch (Exception e) {
                fail("The URI is malformed: port cannot be parsed!", start + index + 1);
            }
        } else {
            //port is not present
            uriObject.setHost(new String(data, start, end - start));
        }
    }
}
/*
 * $Log$
 */